package com.tfswx.jcyw.ruleenginedesigner.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.tfswx.jcyw.ruleenginedesigner.dao.GzyqXtFfMapper;
import com.tfswx.jcyw.ruleenginedesigner.dao.model.GzyqXtFf;
import com.tfswx.jcyw.ruleenginedesigner.dto.ffgl.*;
import com.tfswx.jcyw.ruleenginedesigner.service.FfService;
import com.tfswx.ruleengine.compute.exception.AppException;
import com.tfswx.ruleengine.compute.gzjy.BaseFn;
import com.tfswx.ruleengine.compute.gzjy.DatabaseClassLoader;
import com.tfswx.ruleengine.database.service.GzyqService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author ricky
 * @date 2021/11/1
 */
@Service
public class FfServiceImpl implements FfService {
    @Resource
    private GzyqXtFfMapper gzyqXtFfMapper;
    @Resource
    private GzyqService gzyqService;

    @Override
    public boolean saveFf(FfSaveInputDTO inputDTO) {
        GzyqXtFf gzyqXtFf = BeanUtil.copyProperties(inputDTO, GzyqXtFf.class);

        validClass(inputDTO.getClassname(), inputDTO.getClassdata());

        gzyqXtFf = gzyqXtFfMapper.get(gzyqXtFf);
        if (gzyqXtFf == null) {
            gzyqXtFf = new GzyqXtFf();
            BeanUtil.copyProperties(inputDTO, gzyqXtFf);
            gzyqXtFf.setSfsc("N");
            gzyqXtFf.setCjsj(new Date());
            gzyqXtFf.setZhxgsj(new Date());
            int i = gzyqXtFfMapper.insert(gzyqXtFf);
            if (i != 1) {
                throw new AppException("添加方法失败");
            }
        } else {
            BeanUtil.copyProperties(inputDTO, gzyqXtFf);
            gzyqXtFf.setZhxgsj(new Date());
            int i = gzyqXtFfMapper.update(gzyqXtFf);

            if (i != 1) {
                throw new AppException("修改方法失败");
            }
        }
        gzyqService.loadFnList();
        return true;
    }

    @Override
    public FfGetOutputDTO getFf(FfGetInputDTO inputDTO) {
        GzyqXtFf gzyqXtFf = BeanUtil.copyProperties(inputDTO, GzyqXtFf.class);
        gzyqXtFf = gzyqXtFfMapper.get(gzyqXtFf);
        return BeanUtil.copyProperties(gzyqXtFf, FfGetOutputDTO.class);
    }

    @Override
    public List<FfQueryOutputDTO> queryFf(FfQueryInputDTO inputDTO) {
        GzyqXtFf gzyqXtFf = BeanUtil.copyProperties(inputDTO, GzyqXtFf.class);
        return gzyqXtFfMapper.queryFf(gzyqXtFf);
    }

    private void validClass(String classname, byte[] classdata) {
        Map<String, byte[]> datas = new HashMap<>();
        datas.put(classname, classdata);
        DatabaseClassLoader<BaseFn> databaseClassLoader = new DatabaseClassLoader<>(BaseFn.class, datas);
        databaseClassLoader.getInstance(classname);
    }
}
